﻿using System.Runtime.Remoting.Messaging;

namespace XieCan.AspMVC.Helpers
{
    public class CallContextHelper
    {
        /// <summary>
        /// 单例模式：保证线程实例唯一
        /// </summary>
        /// <typeparam name="Class">带无参构造函数的类</typeparam>
        /// <param name="name">实例名称，默认使用该类的类名</param>
        /// <returns>该类的实例</returns>
        public static Class Single<Class>(string name = "")
            where Class : class, new()
        {
            return Single<Class, Class>(name);
        }

        /// <summary>
        /// 单例模式：保证线程实例唯一
        /// </summary>
        /// <typeparam name="Class">带无参构造函数的类</typeparam>
        /// <typeparam name="Interface">该类实现的接口</typeparam>
        /// <param name="name">实例名称，默认使用该类的类名</param>
        /// <returns>该类实现的接口</returns>
        public static Interface Single<Class, Interface>(string name = "")
            where Class : Interface, new()
        {
            var key = string.IsNullOrWhiteSpace(name) ? typeof(Class).Name : name;
            Interface @interface = (Interface)CallContext.GetData(key);
            if (@interface == null)
            {
                @interface = new Class();
                CallContext.SetData(key, @interface);
            }
            return @interface;
        }
    }
}
